from Common.EventHandle import EventHandle

from Calendar.Calendar import *
from Misc.QuoteType import *
from FinancialAsset.AssetFactory import *

from DataFeeder.QueryFundTopHolding import *
from DataFeeder.QueryQuote import *

class MutualFundHolding(EventHandle):
	
	def __init__(self, start_date, end_date, top_size):
	
		self.top_size = top_size
		
		cld = TradingCalendar()
		data_dates = cld.date_series(start_date, end_date, Frequency.Quarterly)	
		
		EventHandle.__init__(self, data_dates)
		
	def create_activities(self, ref_date, portf = None):
	
		print 'running info...', ref_date.isoformat()
		
		holding = portf.holding(ref_date)
		print '   step 1, acquring holding completed...', len(holding)
		
		nav = portf.nav(ref_date)
		print '   step 2, acquring nav completed...', nav
		
		top_holding = query_fund_top_holding(ref_date, topN = self.top_size)
		stock_pool = set()
		for k in top_holding.keys():
			stock_pool.add(AssetFactory().acquire_asset('STOCK', k[1]))
			
		print '   step 3, acquring stock pool completed...', len(stock_pool)
		
		activities = []
		for sec, quantity in holding.iteritems():
			if sec.type_name() == 'STOCK':
					
				close = QuoteRegister().get_stock_quote(ref_date, sec.ticker(), QuoteType.CLOSE)
				cash = AssetFactory().acquire_asset('CASH', sec.currency())
				
				activities.append((ref_date, sec, -quantity))
				activities.append((ref_date, cash, quantity*close))
		
		for sec in stock_pool:
			
			close = QuoteRegister().get_stock_quote(ref_date, sec.ticker(), QuoteType.CLOSE)
			
			if close and close > 0:
			
				cash = AssetFactory().acquire_asset('CASH', sec.currency())
				quantity = int(nav/len(stock_pool)/close)
				
				activities.append((ref_date, sec, quantity))
				activities.append((ref_date, cash, -quantity*close))
				
		print '   step 4, create activies completed...', len(activities)
		
		return activities
		
	@staticmethod	
	def event_name():
		return 'MutualFundHolding'
